package com.hgb.mall.portal.services.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.hgb.mall.common.exception.ApiException;
import com.hgb.mall.mbg.entity.*;
import com.hgb.mall.mbg.mapper.*;
import com.hgb.mall.portal.dao.PortalProductDao;
import com.hgb.mall.portal.domain.PmsPortalProductDetail;
import com.hgb.mall.portal.domain.PmsProductCategoryNode;
import com.hgb.mall.portal.services.PmsPortalProductService;
import org.mybatis.dynamic.sql.SortSpecification;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * 前台订单管理Service实现类
 * Created by hgb on hgb/4/6.
 */
@Service
public class PmsPortalProductServiceImpl implements PmsPortalProductService {
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsProductCategoryMapper productCategoryMapper;
    @Autowired
    private PmsBrandMapper brandMapper;
    @Autowired
    private PmsProductAttributeMapper productAttributeMapper;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PortalProductDao portalProductDao;
    @Autowired
    private PmsCommentMapper commentMapper;

    @Override
    public List<PmsProduct> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize, Integer sort) {
        PageHelper.startPage(pageNum, pageSize);
        SortSpecification order = PmsProductDynamicSqlSupport.sale.descending();
        switch (sort) {
            case 1:
                order = PmsProductDynamicSqlSupport.id.descending();
                break;
            case 2:
                order = PmsProductDynamicSqlSupport.sale.descending();
                break;
            case 3:
                order = PmsProductDynamicSqlSupport.price;
                break;
            case 4:
                order = PmsProductDynamicSqlSupport.price.descending();
                break;
        }
        //1->按新品；2->按销量；3->价格从低到高；4->价格从高到低
        SortSpecification finalOrder = order;
        return productMapper.select(c -> c
                .where(PmsProductDynamicSqlSupport.deleteStatus, isEqualTo(0))
                .and(PmsProductDynamicSqlSupport.name, isLikeWhenPresent(keyword).then(s -> "%" + s + "%"))
                .and(PmsProductDynamicSqlSupport.brandId, isEqualToWhenPresent(brandId))
                .and(PmsProductDynamicSqlSupport.productCategoryId, isEqualToWhenPresent(productCategoryId))
                .orderBy(finalOrder)
        );
    }

    @Override
    public List<PmsProductCategoryNode> categoryTreeList() {
        List<PmsProductCategory> allList = productCategoryMapper.select(c -> c);
        return allList.stream()
                      .filter(item -> item.getParentId().equals(0L))
                      .map(item -> covert(item, allList)).collect(Collectors.toList());
    }

    @Override
    public PmsPortalProductDetail detail(Long id) {
        PmsPortalProductDetail result = new PmsPortalProductDetail();
        //获取商品信息
        PmsProduct product = productMapper.selectByPrimaryKey(id).orElseThrow(() -> new ApiException("无此产品"));
        result.setProduct(product);
        //获取品牌信息
        PmsBrand brand = brandMapper.selectByPrimaryKey(product.getBrandId())
                                    .orElseThrow(() -> new ApiException("无此品牌"));
        result.setBrand(brand);
        //获取商品属性信息
        List<PmsProductAttribute> productAttributeList =
                productAttributeMapper.select(c -> c
                        .where(PmsProductAttributeDynamicSqlSupport.productAttributeCategoryId, isEqualTo(product
                                .getProductAttributeCategoryId()))
                );
        result.setProductAttributeList(productAttributeList);
        //获取商品属性值信息
        if (CollUtil.isNotEmpty(productAttributeList)) {
            List<Long> attributeIds = productAttributeList.stream().map(PmsProductAttribute::getId)
                                                          .collect(Collectors.toList());
            List<PmsProductAttributeValue> productAttributeValueList =
                    productAttributeValueMapper.select(c -> c
                            .where(PmsProductAttributeValueDynamicSqlSupport.productId, isEqualTo(product.getId()))
                            .and(PmsProductAttributeValueDynamicSqlSupport.productAttributeId, isIn(attributeIds))
                    );
            result.setProductAttributeValueList(productAttributeValueList);
        }
        //获取商品SKU库存信息
        List<PmsSkuStock> skuStockList = skuStockMapper
                .select(c -> c.where(PmsSkuStockDynamicSqlSupport.productId, isEqualTo(product.getId())));
        result.setSkuStockList(skuStockList);
        //商品阶梯价格设置
        if (product.getPromotionType() == 3) {
            List<PmsProductLadder> productLadderList =
                    productLadderMapper.select(c -> c
                            .where(PmsProductLadderDynamicSqlSupport.productId, isEqualTo(product.getId())));
            result.setProductLadderList(productLadderList);
        }
        //商品满减价格设置
        if (product.getPromotionType() == 4) {
            List<PmsProductFullReduction> productFullReductionList =
                    productFullReductionMapper.select(c -> c
                            .where(PmsProductFullReductionDynamicSqlSupport.productId, isEqualTo(product.getId())));
            result.setProductFullReductionList(productFullReductionList);
        }
        //商品可用优惠券
        result.setCouponList(portalProductDao.getAvailableCouponList(product.getId(), product.getProductCategoryId()));
        result.setCommentList(commentMapper.select(c->c
                .where(PmsCommentDynamicSqlSupport.productId,isEqualTo(product.getId()))
                .orderBy(PmsCommentDynamicSqlSupport.id.descending()).limit(2)));
        return result;
    }


    /**
     * 初始对象转化为节点对象
     */
    private PmsProductCategoryNode covert(PmsProductCategory item, List<PmsProductCategory> allList) {
        PmsProductCategoryNode node = new PmsProductCategoryNode();
        BeanUtils.copyProperties(item, node);
        List<PmsProductCategoryNode> children = allList.stream()
                                                       .filter(subItem -> subItem.getParentId().equals(item.getId()))
                                                       .map(subItem -> covert(subItem, allList))
                                                       .collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
}
